<template>
  <el-form :inline="true"  class="demo-form-inline">
      <el-form-item label="BOM编号">
        <el-input v-model="bomparameter.BomCode" placeholder="请输入BOM编号" clearable />
      </el-form-item>
      <el-form-item label="物料编号">
         <el-input v-model="bomparameter.MaterialNumber" placeholder="请输入材料编号" clearable />
      </el-form-item>
     
      <el-form-item>
        <el-button type="primary" @click="getBom()">查询</el-button>
      </el-form-item>
         <el-form-item>
        <el-upload
      v-model:file-list="fileList"
      class="upload-demo"
      action="http://localhost:9991/api/MaterialManagement/ImportExcel"
      multiple
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-remove="beforeRemove"
      :limit="3"
      :on-exceed="handleExceed"
      :on-success="handleSuccess"
    >
      <el-button type="primary">批量导入</el-button>
    
    </el-upload>
      </el-form-item>
      <br>
        <el-form-item>
        <el-button type="primary" @click="toAdddialog()">添加</el-button>
      </el-form-item>
  
      <el-form-item>
        <el-button type="danger" @click="delAllBom()">批量删除</el-button>
      </el-form-item>
      
    </el-form>
  
    <el-table
      ref="multipleTableRef"
      :data="tableData"
      row-key="id"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection"  width="55" />
      <el-table-column fixed prop="id" label="Id" width="150" />
      <el-table-column prop="bomCode" label="bom编号" width="120" />
      <el-table-column prop="materialNumber" label="物料编号" width="120" />
      <el-table-column prop="materialName" label="物料名称" width="120" />
      <el-table-column prop="supplier" label="供应商" width="120" />
      <el-table-column prop="versionNumber" label="版本" width="120" />
      <el-table-column prop="remarks" label="备注" width="120" />
      <el-table-column prop="states" label="状态" width="120" >
   <template #default="scope">
            <el-tag type="primary" v-if="scope.row.states==1">正常</el-tag>
            <el-tag type="danger" v-if="scope.row.states==2">已删除</el-tag>
            <el-tag type="warning" v-if="scope.row.states==3">已禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="toupdatedialog(scope.row)">
            修改
          </el-button>
          <el-button link type="primary" size="small" @click="delBom(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  <!-- 添加BOM对话框 -->
  
   <el-dialog
      v-model="adddialogVisible"
      title="添加"
      width="700"
    >
   <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
    >
      <el-form-item label="BOM编码" prop="bomCode">
        <el-input v-model="ruleForm.bomCode" />
      </el-form-item>
   
   <el-form-item label="物料编码" prop="materialNumber">
     <el-button  type="primary" size="small" @click="toMaterialdialog"><el-icon><Search /></el-icon></el-button>   <el-input v-model="ruleForm.materialNumber" style="width: 450px;padding-left: 10px;"/>
      </el-form-item>
  
       <el-form-item label="物料名称" prop="materialName">
        <el-input v-model="ruleForm.materialName" />
      </el-form-item>
  
       <el-form-item label="供应商" prop="supplier">
        <el-input v-model="ruleForm.supplier" />
      </el-form-item>
  
       <el-form-item label="版本号" prop="versionNumber">
        <el-input-number 
          v-model="ruleForm.versionNumber" 
          :min="1"
          :controls="true"
          @change="handleVersionChange"
        />
      </el-form-item>
  
   <el-form-item label="状态" prop="states">
        
        <el-radio-group v-model="ruleForm.states">
        <el-radio :value="1" size="large">正常</el-radio>
        <el-radio :value="2" size="large">已删除</el-radio>
        <el-radio :value="3" size="large">已禁用</el-radio>
      </el-radio-group>
      </el-form-item>
  
       <el-form-item label="备注说明" prop="remarks">
        <el-input v-model="ruleForm.remarks" />
      </el-form-item>
  
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          保存
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
    </el-dialog>
  
  
    <!-- 修改BOM对话框 -->
  
   <el-dialog
      v-model="updatedialogVisible"
      title="添加"
      width="700"
    >
   <el-form
      ref="updateruleFormRef"
      style="max-width: 600px"
      :model="updateruleForm"
      :rules="updaterules"
      label-width="auto"
    >
      <el-form-item label="BOM编码" prop="bomCode">
        <el-input v-model="updateruleForm.bomCode" />
      </el-form-item>
   
   <el-form-item label="物料编码" prop="materialNumber">
        <el-button type="primary" size="small" @click="toUpdateMaterialdialog"><el-icon><Search /></el-icon></el-button>
        <el-input v-model="updateruleForm.materialNumber" style="width: 450px;padding-left: 10px;"/>
      </el-form-item>
  
       <el-form-item label="物料名称" prop="materialName">
        <el-input v-model="updateruleForm.materialName" />
      </el-form-item>
  
       <el-form-item label="供应商" prop="supplier">
        <el-input v-model="updateruleForm.supplier" />
      </el-form-item>
  
       <el-form-item label="版本号" prop="versionNumber">
        <el-input-number 
          v-model="updateruleForm.versionNumber" 
          :min="1"
          :controls="true"
          @change="handleVersionChange"
        />
      </el-form-item>
  
   <el-form-item label="状态" prop="states">
        
        <el-radio-group v-model="updateruleForm.states">
        <el-radio :value="1" size="large">正常</el-radio>
        <el-radio :value="2" size="large">已删除</el-radio>
        <el-radio :value="3" size="large">已禁用</el-radio>
      </el-radio-group>
      </el-form-item>
  
       <el-form-item label="备注说明" prop="remarks">
        <el-input v-model="updateruleForm.remarks" />
      </el-form-item>
  
      <el-form-item>
        <el-button type="primary" @click="updatesubmitForm(updateruleFormRef)">
          保存
        </el-button>
        <el-button @click="upresetForm()">重置</el-button>
      </el-form-item>
    </el-form>
    </el-dialog>
  
  
  
      <!-- 显示物料对话框 -->
  
   <el-dialog
      v-model="Materialdialog"
      title="信息"
      width="700"
  >
      <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="物料编号">
              <el-input v-model="materialparameter.MaterialCode" placeholder="请输入物料编号" clearable />
          </el-form-item>
          <el-form-item label="物料批次">
              <el-input v-model="materialparameter.Batch" placeholder="请输入物料批次" clearable />
          </el-form-item>
          <el-form-item>
              <el-button type="primary" @click="getMaterial()">
                  <el-icon><Search /></el-icon>
              </el-button>
          </el-form-item>
      </el-form>
  
      <el-table
          ref="singleTableRef"
          :data="tableDatas"
          highlight-current-row
          style="width: 100%"
          @current-change="handleCurrentChange"
      >
          <el-table-column width="50">
              <template #default="scope">
                  <el-radio 
                      v-model="selectedRow" 
                      :label="scope.row.materialCode" 
                      @change="handleRadioChange(scope.row)"
                  >&nbsp;</el-radio>
              </template>
          </el-table-column>
          <el-table-column type="index" width="50" />
          <el-table-column property="materialCode" label="物料编码" width="120" />
          <el-table-column property="materialunit" label="物料描述" width="120" />
          <el-table-column property="batch" label="物料批次" />
      </el-table>
  
      <!-- 分页 -->
      <el-pagination
          v-model:current-page="materialPage.PageIndex"
          v-model:page-size="materialPage.PageSize"
          :page-sizes="[10, 15, 20, 25,30]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="materialPage.totalCount"
      />
  
      <template #footer>
          <span class="dialog-footer">
              <el-button @click="Materialdialog = false">取消</el-button>
              <el-button type="primary" @click="confirmMaterialSelection">
                  确定
              </el-button>
          </span>
      </template>
  </el-dialog>
  
  <!-- 修改物料对话框 -->
  <el-dialog
      v-model="updateMaterialdialog"
      title="信息"
      width="700"
  >
      <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="物料编号">
              <el-input v-model="materialparameter.MaterialCode" placeholder="请输入物料编号" clearable />
          </el-form-item>
          <el-form-item label="物料批次">
              <el-input v-model="materialparameter.Batch" placeholder="请输入物料批次" clearable />
          </el-form-item>
          <el-form-item>
              <el-button type="primary" @click="getMaterial()">
                  <el-icon><Search /></el-icon>
              </el-button>
          </el-form-item>
      </el-form>
  
      <el-table
          ref="updateSingleTableRef"
          :data="tableDatas"
          highlight-current-row
          style="width: 100%"
          @current-change="handleUpdateCurrentChange"
      >
          <el-table-column width="50">
              <template #default="scope">
                  <el-radio 
                      v-model="updateSelectedRow" 
                      :label="scope.row.materialCode" 
                      @change="handleUpdateRadioChange(scope.row)"
                  >&nbsp;</el-radio>
              </template>
          </el-table-column>
          <el-table-column type="index" width="50" />
          <el-table-column property="materialCode" label="物料编码" width="120" />
          <el-table-column property="materialunit" label="物料描述" width="120" />
          <el-table-column property="batch" label="物料批次" />
      </el-table>
  
      <!-- 分页 -->
      <el-pagination
          v-model:current-page="materialPage.PageIndex"
          v-model:page-size="materialPage.PageSize"
          :page-sizes="[10, 15, 20, 25,30]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="materialPage.totalCount"
      />
  
      <template #footer>
          <span class="dialog-footer">
              <el-button @click="updateMaterialdialog = false">取消</el-button>
              <el-button type="primary" @click="confirmUpdateMaterialSelection">
                  确定
              </el-button>
          </span>
      </template>
  </el-dialog>
  
  <!-- 分页 -->
      <el-pagination
        v-model:current-page="page.PageIndex"
        v-model:page-size="page.PageSize"
        :page-sizes="[10, 15, 20, 25,30]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.totalCount"
      />
  </template>
  
  <script lang="ts" setup>
  import {ref,reactive,onMounted,watch} from 'vue'
  import http from '@/api/http'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import type { TableInstance } from 'element-plus'
  import { Search } from '@element-plus/icons-vue'
  
  const handleClick = () => {
    console.log('click')
  }
  
  //分页参数
  const page=reactive({
    PageIndex:1,
    PageSize:10,
    totalCount:0
  })
  //bom查询参数
  const bomparameter=reactive({
  BomCode:'',
  MaterialNumber:''
  })
  //BOM数据源
  const tableData = ref([])
  //获取显示数据
  const  getBom=()=>{
    console.log(111,page)
  http.get("/api/MaterialManagement/GetBom?PageIndex="+page.PageIndex+"&PageSize="+page.PageSize+"&BomCode="+bomparameter.BomCode+"&MaterialNumber="+bomparameter.MaterialNumber).then(res=>{
    console.log("res",res)
    tableData.value=res.data.items
    page.totalCount=res.data.totalCount
  })
  }
  //监听分页
   watch((page),()=>{
  getBom();
  },{deep:true})
  
  //定义添加弹出框残
  const adddialogVisible = ref(false)
  //添加弹出框
  const toAdddialog=()=>{
  adddialogVisible.value=true;
  }
  
  //#region    添加bom数据
  const ruleFormRef = ref<FormInstance>()
  const ruleForm = reactive({
   "id": 0,
    "bomCode": "",
    "materialNumber": "",
    "materialName": "",
    "supplier": "",
    "versionNumber": 1,
    "states": 1,
    "remarks": ""
  })
  
  const locationOptions = ['Home', 'Company', 'School']
  
  const rules = reactive<FormRules>({
    bomCode: [
      { required: true, message: '请输入BOM编号', trigger: 'blur' },
      { min: 5, max: 15, message: 'BOM编号在5到15字符之间', trigger: 'blur' },
    ],
     materialNumber: [
      { required: true, message: '请输入物料编码', trigger: 'blur' },
      { min: 1, max: 15, message: '物料编码在1到15字符之间', trigger: 'blur' },
    ],
     materialName: [
      { required: true, message: '请输入物料名称', trigger: 'blur' },
      { min: 2, max: 15, message: '物料名称在2到15字符之间', trigger: 'blur' },
    ],
     supplier: [
      { required: true, message: '请输入供应商', trigger: 'blur' },
      { min: 2, max: 15, message: '供应商在2到15字符之间', trigger: 'blur' },
    ],
     versionNumber: [
      { required: true, message: '请输入版本号', trigger: 'blur' },
      { type: 'number', min: 1, message: '版本号不能小于1', trigger: 'blur' }
    ],
    
     remarks: [
      { required: true, message: '请输入备注说明', trigger: 'blur' },
      { min: 2, max: 50, message: '备注说明在2到15字符之间', trigger: 'blur' },
    ],
    
  })
  
  const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {
        console.log('submit!')
  http.post("/api/MaterialManagement/AddBom",ruleForm).then(res=>{
  ElMessage.success(res.message);
  ruleForm.bomCode="";
  ruleForm.materialNumber="";
  ruleForm.materialName="";
  ruleForm.supplier="";
  ruleForm.versionNumber=1;
  ruleForm.remarks="";
  
  adddialogVisible.value=false;
  getBom();
  })
  
      } else {
        console.log('error submit!', fields)
      }
    })
  }
  
  const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
  }
  
  const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
  }))
  
  
  //#endregion
  
  
  //定义修改弹出框残
  const updatedialogVisible = ref(false)
  //添加弹出框
  const toupdatedialog=(row:any)=>{
    Object.assign(updateruleForm,row);
  updatedialogVisible.value=true;
  }
  
  //#region    修改bom数据
  const updateruleFormRef = ref<FormInstance>()
  const updateruleForm = reactive({
   "id": 0,
    "bomCode": "",
    "materialNumber": "",
    "materialName": "",
    "supplier": "",
    "versionNumber": 1,
    "states": 1,
    "remarks": ""
  })
  
  const updatelocationOptions = ['Home', 'Company', 'School']
  
  const updaterules = reactive<FormRules>({
    bomCode: [
      { required: true, message: '请输入BOM编号', trigger: 'blur' },
      { min: 5, max: 15, message: 'BOM编号在5到15字符之间', trigger: 'blur' },
    ],
     materialNumber: [
      { required: true, message: '请输入物料编码', trigger: 'blur' },
      { min: 1, max: 15, message: '物料编码在1到15字符之间', trigger: 'blur' },
    ],
     materialName: [
      { required: true, message: '请输入物料名称', trigger: 'blur' },
      { min: 2, max: 15, message: '物料名称在2到15字符之间', trigger: 'blur' },
    ],
     supplier: [
      { required: true, message: '请输入供应商', trigger: 'blur' },
      { min: 2, max: 15, message: '供应商在2到15字符之间', trigger: 'blur' },
    ],
     versionNumber: [
      { required: true, message: '请输入版本号', trigger: 'blur' },
      { type: 'number', min: 1, message: '版本号不能小于1', trigger: 'blur' }
    ],
    
     remarks: [
      { required: true, message: '请输入备注说明', trigger: 'blur' },
      { min: 2, max: 50, message: '备注说明在2到15字符之间', trigger: 'blur' },
    ],
    
  })
  
  const updatesubmitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {
        console.log('submit!')
  http.post("/api/MaterialManagement/UpDateBom",updateruleForm).then(res=>{
  ElMessage.success(res.message);
  updatedialogVisible.value=false;
  getBom();
  })
  
      } else {
        console.log('error submit!', fields)
      }
    })
  }
  
  const updateresetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
  }
  
  const updateoptions = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
  }))
  
  
  //#endregion
  
  //删除
  const delBom=(id:any)=>{
  
   ElMessageBox.confirm(
      '您确认删除吗?',
      'Warning',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(() => {
        http.post('/api/MaterialManagement/DelBom',id).then(res=>{
  ElMessage.success(res.message);
  getBom();
  })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '删除已取消',
        })
      })
  }
  
  //批量删除
  const multipleTableRef = ref<TableInstance>()
  const multipleSelection = ref([]) 
  const bomId=ref([])
  const handleSelectionChange = (val:any) => {
    bomId.value = val.map((item:any)=>item.id);
  }
  
  //批量删除
  const delAllBom=()=>{
   
   ElMessageBox.confirm(
      '您确认删除吗?',
      'Warning',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(() => {
        if(bomId.value.length==0)
        {
  return ElMessage.error("请至少选择一项需要删除的列");
        }
        http.post('/api/MaterialManagement/DelBom',bomId.value.toString()).then(res=>{
  ElMessage.success(res.message);
  getBom();
  })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '删除已取消',
        })
      })
  }
  //生命周期 钩子函数
  onMounted(()=>{
    getBom();
    getMaterial();
    getSmartDisplayWall();
  })
  
  
  //#region 导入
  import type { UploadProps, UploadUserFile } from 'element-plus'
  
  const fileList = ref<UploadUserFile[]>([
   
  ])
  
  const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
    console.log(file, uploadFiles)
  }
  
  const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
    console.log(uploadFile)
  }
  
  const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
    ElMessage.warning(
      `The limit is 3, you selected ${files.length} files this time, add up to ${
        files.length + uploadFiles.length
      } totally`
    )
  }
  
  const beforeRemove: UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
    return ElMessageBox.confirm(
      `Cancel the transfer of ${uploadFile.name} ?`
    ).then(
      () => true,
      () => false
    )
  }
  
  // 添加上传成功回调
  const handleSuccess: UploadProps['onSuccess'] = (response, uploadFile, uploadFiles) => {
    ElMessage.success('上传成功')
    // 更新文件列表或执行其他操作
   
    // 如果需要刷新页面，取消下面的注释
  
    location.reload()
  }
  //#endregion
  
  //#region   显示物料信息
  const Materialdialog=ref(false)
  
  const toMaterialdialog=()=>{
  Materialdialog.value=true;
  selectedRow.value = '';
  currentRow.value = null;
  }
  
  const currentRow = ref()
  const singleTableRef = ref<TableInstance>()
  
  const setCurrent = (row:any) => {
    singleTableRef.value!.setCurrentRow(row)
    Materialdialog.value=false;
  }
  const handleCurrentChange = (val: any) => {
    if (val) {
      currentRow.value = val;
      selectedRow.value = val.materialCode;
    }
  }
  const tableDatas = ref([])
  //物料分页参数
  const materialPage=reactive({
    PageIndex:1,
    PageSize:10,
    totalCount:0,
  })
  //物料查询参数
  const materialparameter=reactive({
    MaterialCode:'',
    Batch:''
  })
  //接受物料信息
  const getMaterial=()=>{
    http.get("/api/MaterialManagement/GetMaterial?PageIndex="+materialPage.PageIndex+"&PageSize="+materialPage.PageSize+"&MaterialCode="+materialparameter.MaterialCode+"&Batch="+materialparameter.Batch+""
    ).then(res => {
      tableDatas.value = res.data.items;
      materialPage.totalCount = res.data.totalCount;
    }).catch(error => {
      ElMessage.error('获取物料数据失败');
    });
  }
  
  //#endregion
  
  
  const handleVersionChange = (value: number) => {
    if (value < 1) {
      ElMessage.warning('版本号不能小于1')
      return false
    }
  }
  
  const confirmMaterialSelection = () => {
    if (currentRow.value) {
      ruleForm.materialNumber = currentRow.value.materialCode;
      Materialdialog.value = false;
    } else {
      ElMessage.warning('请选择一条物料记录');
    }
  }
  
  // 监听物料分页变化
  watch(materialPage, () => {
    getMaterial();
  }, { deep: true });
  
  const selectedRow = ref('') // 用于存储选中的行的 materialCode
  
  const handleRadioChange = (row: any) => {
      currentRow.value = row;
      singleTableRef.value?.setCurrentRow(row);
  }
  
  // 在 script 部分添加以下代码
  const updateMaterialdialog = ref(false)
  const updateSelectedRow = ref('')
  const updateSingleTableRef = ref<TableInstance>()
  
  const toUpdateMaterialdialog = () => {
      updateMaterialdialog.value = true;
      updateSelectedRow.value = '';
  }
  
  const handleUpdateRadioChange = (row: any) => {
      currentRow.value = row;
      updateSingleTableRef.value?.setCurrentRow(row);
  }
  
  const handleUpdateCurrentChange = (val: any) => {
      if (val) {
          currentRow.value = val;
          updateSelectedRow.value = val.materialCode;
      }
  }
  
  const confirmUpdateMaterialSelection = () => {
      if (currentRow.value) {
          updateruleForm.materialNumber = currentRow.value.materialCode;
          
          updateMaterialdialog.value = false;
      } else {
          ElMessage.warning('请选择一条物料记录');
      }
  }
  
//修改重置按钮
const upresetForm=()=>{
  Object.assign(updateruleForm, {
    id: 0,
    bomCode: "",
    materialNumber: "",
    materialName: "",
    supplier: "",
    versionNumber: 1,
    states: 1,
    remarks: ""
  })

}



  
  const getSmartDisplayWall=()=>{
    http.get("/api/MaterialManagement/GetSmartDisplayWall?days=7").then(res=>{
      console.log(766,res);
    })
  }
  
  
  
  </script>